<template>
  <div class="logincontainer">
    <div class="avater">
      <img src="../../assets/images/1676358140646.png" alt="" />
    </div>
    <div class="loginform">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账户" prop="pass">
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
            type="text"
            v-model="ruleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {login} from '../../api/user'
import { mapMutations } from "vuex";
import { USERLOGIN, USERLOGOUT } from "../../store/types";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    return {
      ruleForm: {
        username: "chaoge",
        password: "123456",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations([USERLOGIN, USERLOGOUT]),
  
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let result=await login(this.ruleForm.username,this.ruleForm.password);
        console.log(result);
        const token=result.data.token;
        if (token != "") {
            // 保存token 用于权限验证
            this[USERLOGIN](token);
            this.$router.push("/main");
          } else {
            this.$message({
              message: "你的账号密码错误",
              type: "error",
            });
          }
        } else {
          console.log("失败!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<!-- //sass的修改 -->
<style lang="less" scoped>
.logincontainer {
  background-color: aquamarine;
  img {
    height: 200px;
    width: 200px;
    border-radius: 50%;
  }
}
.loginform,
.avater {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
